package net.jarang.android.saleoffline.domain;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.jarang.android.saleoffline.SaleContext;
import net.jarang.android.support.http.DefaultHttpInvocator;
import net.jarang.android.support.http.HttpResult;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

public class SaleDao {
	public static final String SALE_SEARCH_URL = "http://jarang.iptime.org:8080/sale/list.json";
	DefaultHttpInvocator httpInvocator = new DefaultHttpInvocator();

	public List<Sale> search(SaleSearch search, int page) {
		List<Sale> sales = new ArrayList<Sale>();
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("page", page);
			params.put("orderByType", search.getOrderByType());
			
			HttpResult result = httpInvocator.get(SALE_SEARCH_URL, params, null);
			JSONArray array = new JSONObject(result.getReturnValue()).getJSONArray("saleList");
			
			Log.v(SaleContext.TAG, array.length() + "");
			
			int arrayLength = array.length();
			for (int i = 0; i < arrayLength; i++) {
				JSONObject object = array.getJSONObject(i);
				Sale sale = new Sale();
				sale.setId(object.getInt("id"));
				sale.setProduct(object.getString("productName"));
				sale.setLocation(object.getString("locationAddress"));
				sale.setShopName(object.getString("shopName"));
				sale.setFromOff(object.getInt("saleOffFrom"));
				sale.setToOff(object.getInt("saleOffTo"));
				sale.setFromDate(object.getString("displaySaleDateFrom"));
				sale.setToDate(object.getString("displaySaleDateTo"));
				sale.setThumbnailImageUrl1(object.getString("photoUrl2"));
				sales.add(sale);
			}
		} catch (Exception e) {
			Log.e(SaleContext.TAG, e.getMessage(), e);
			throw new IllegalArgumentException();
		}
		return sales;
	}

	public SaleSearch makeSaleSearch() {
		SaleSearch search = new SaleSearch();
		search.setOrderByType("DATE");
		return search;
	}
}
